before_all do
    ensure_bundle_exec
end

lane :build do |options|
    setup_ci
    sync_code_signing
    sync_code_signing(type: 'appstore')

    # do this after committing the version bump but before building the app
    if is_ci
      update_code_signing_settings(
        path: "iSH.xcodeproj",
        targets: "iSH",
        use_automatic_signing: false,
        profile_uuid: ENV["sigh_app.ish.iSH_development"],
      )
      update_code_signing_settings(
        path: "iSH.xcodeproj",
        targets: "iSHFileProvider",
        use_automatic_signing: false,
        profile_uuid: ENV["sigh_app.ish.iSH.FileProvider_development"],
      )
    end

    config = options[:config]
    config = "app/#{config}.xcconfig" if config
    build_app(
      project: "iSH.xcodeproj",
      scheme: "iSH",
      xcconfig: config,
      xcargs: "DEVELOPMENT_TEAM=#{CredentialsManager::AppfileConfig.try_fetch_value(:team_id)}",
      output_name: options[:output],
    )
end

lane :upload_build do
    last_tag = `git describe --tags --abbrev=0 --match builds/\*`.chomp
    shortlog = `git shortlog #{last_tag}..HEAD`
    if shortlog.empty?
        UI.error "No commits since last build"
        next
    end
    changelog = "Automated daily build"
    testflight_changelog = changelog + "\n" + File.read("footer.txt") + shortlog

    app_store_connect_api_key
    latest = latest_testflight_build_number.to_s.scan(/^\d+(?=\.|$)/).first.to_i
    build_number = latest + 1
    Dir.chdir("..") do
        sh "agvtool", "new-version", build_number.to_s
    end
    commit_version_bump(
        xcodeproj: "iSH.xcodeproj",
        message: "Bump version to #{build_number}",
        force: true,
    )
    tag = "builds/#{build_number}"
    add_git_tag(tag: tag)

    build
    puts testflight_changelog
    upload_to_testflight(
        ipa: "iSH.ipa",
        changelog: testflight_changelog,
        wait_processing_interval: 300, # the processing is expected to take a total of 5 hours, so don't logspam too much
        distribute_external: true,
        groups: ["People"],
    )

    # uploading a build takes about 5 hours, so merge master back in if there have been any commits during that
    sh "git pull --no-rebase"
    push_to_git_remote
    set_github_release(
        repository_name: "ish-app/ish",
        tag_name: tag,
        commitish: nil, # the tag better exist
        name: "Build #{build_number}",
        description: changelog,
        is_prerelease: true,
        upload_assets: ["iSH.ipa", "iSH.app.dSYM.zip"],
        api_token: ENV["GH_TOKEN"],
    )
end
